<template>
  <div>
    <div class="header">
      <el-select v-model="value" @change="changeValue" placeholder="请选择周数">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <div class="right">
        <el-button class="info" type="primary" plain @click="exportForm"
          >导出信息</el-button
        >
        <el-input
          placeholder="请输入关键字"
          v-model="input"
          clearable
          @change="change"
        ></el-input>
        <el-button
          class="sousuo"
          type="primary"
          icon="el-icon-search"
          @click="search"
          >搜索</el-button
        >
      </div>
    </div>
    <el-table
      element-loading-background="rgba(255, 255, 255, .5)"
      element-loading-text="小主别急，好运正在路上"
      element-loading-spinner="el-icon-loading"
      :data="tableData"
      id="mainFrame"
      v-loading="Loading"
    >
      <el-table-column prop="name" label="姓名" align="center">
      </el-table-column>
      <el-table-column prop="classNumber" label="班级" align="center">
      </el-table-column>
      <el-table-column prop="studentId" label="学号" align="center">
      </el-table-column>
      <el-table-column prop="monday" label="周一" align="center">
        <template slot-scope="scope">
          <div slot="reference" class="name-wrapper">
            {{
              Number(
                (scope.row.monday / 3600000)
                  .toString()
                  .match(/^\d+(?:\.\d{0,1})?/)
              )
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="tuesday" label="周二" align="center">
        <template slot-scope="scope">
          <div slot="reference" class="name-wrapper">
            {{
              Number(
                (scope.row.tuesday / 3600000)
                  .toString()
                  .match(/^\d+(?:\.\d{0,1})?/)
              )
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="wednesday" label="周三" align="center"
        ><template slot-scope="scope">
          <div slot="reference" class="name-wrapper">
            {{
              Number(
                (scope.row.wednesday / 3600000)
                  .toString()
                  .match(/^\d+(?:\.\d{0,1})?/)
              )
            }}
          </div>
        </template></el-table-column
      >
      <el-table-column prop="thursday" label="周四" align="center">
        <template slot-scope="scope">
          <div slot="reference" class="name-wrapper">
            {{
              Number(
                (scope.row.thursday / 3600000)
                  .toString()
                  .match(/^\d+(?:\.\d{0,1})?/)
              )
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="friday" label="周五" align="center">
        <template slot-scope="scope">
          <div slot="reference" class="name-wrapper">
            {{
              Number(
                (scope.row.friday / 3600000)
                  .toString()
                  .match(/^\d+(?:\.\d{0,1})?/)
              )
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="saturday" label="周六" align="center">
        <template slot-scope="scope">
          <div slot="reference" class="name-wrapper">
            {{
              Number(
                (scope.row.saturday / 3600000)
                  .toString()
                  .match(/^\d+(?:\.\d{0,1})?/)
              )
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="sunday" label="周日" align="center">
        <template slot-scope="scope">
          <div slot="reference" class="name-wrapper">
            {{
              Number(
                (scope.row.sunday / 3600000)
                  .toString()
                  .match(/^\d+(?:\.\d{0,1})?/)
              )
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="totalTime" label="总时长" align="center">
        <template slot-scope="scope">
          <div slot="reference" class="name-wrapper">
            {{
              Number(
                (scope.row.totalTime / 3600000)
                  .toString()
                  .match(/^\d+(?:\.\d{0,1})?/)
              )
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="isStandard" label="是否合格" align="center">
        <template slot-scope="{ row }">
          <el-row
            ><el-button
              size="mini"
              :type="row.isStandard === true ? 'success' : 'danger'"
              >{{ row.isStandard === true ? "合格" : "不合格" }}</el-button
            ></el-row
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      style="text-align: center"
      layout="prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-count="pageCount"
      :page-size="pageSize"
      :total="total"
    >
    </el-pagination>
  </div>
</template>

<script>
import FileSaver from "./file-saver";
import XLSX from "./xlsx";
function yearDay(long) {
  var time = new Date(long * 1000);
  var year = time.getFullYear();
  var month =
    time.getMonth() + 1 < 10
      ? "0" + (time.getMonth() + 1)
      : time.getMonth() + 1;
  var date = time.getDate() < 10 ? "0" + time.getDate() : time.getDate();
  var dates =
    parseInt(time.getDate()) + 6 < 10
      ? "0" + (parseInt(time.getDate()) + 6)
      : parseInt(time.getDate()) + 6;
  var yearday = { year, month, date, dates };
  return yearday;
}
const year = new Date().getFullYear();
function whichWeek(year) {
  var d = new Date(year, 8, 5);
  while (d.getDay() != 1) {
    d.setDate(d.getDate() + 1);
  }
  let arr = [];
  let longnum = d.setDate(d.getDate());
  let oneitem = yearDay(longnum / 1000);
  oneitem.last = yearDay(longnum / 1000 + 86400 * 6);
  arr.push(oneitem);
  var lastStr;
  for (var i = 1; i < 15; i++) {
    let long = d.setDate(d.getDate() + 7);
    let obj = yearDay(long / 1000);
    obj.last = yearDay(long / 1000 + 86400 * 6);
    lastStr = long + 86400000 * 6;
    arr.push(obj);
  }
  if (lastStr < +new Date(year + 1, 0, 1)) {
    let obj = yearDay(lastStr / 1000 + 86400);
    obj.last = yearDay(+new Date(year + 1, 0, 1) / 1000 - 86400);
    arr.push(obj);
  } else {
    arr[arr.length - 1].last = yearDay(
      +new Date(year + 1, 0, 1) / 1000 - 86400
    );
  }
  return arr;
}
function whichWeeks(year) {
  var d = new Date(year, 8, 11);
  while (d.getDay() != 1) {
    d.setDate(d.getDate() + 1);
  }
  let arr = [];
  let longnum = d.setDate(d.getDate());
  let oneitem = yearDay(longnum / 1000);
  oneitem.last = yearDay(longnum / 1000 + 86400 * 6);
  arr.push(oneitem);
  var lastStr;
  for (var i = 1; i < 15; i++) {
    let long = d.setDate(d.getDate() + 7);
    let obj = yearDay(long / 1000);
    obj.last = yearDay(long / 1000 + 86400 * 6);
    lastStr = long + 86400000 * 6;
    arr.push(obj);
  }
  if (lastStr < +new Date(year + 1, 0, 1)) {
    let obj = yearDay(lastStr / 1000 + 86400);
    obj.last = yearDay(+new Date(year + 1, 0, 1) / 1000 - 86400);
    arr.push(obj);
  } else {
    arr[arr.length - 1].last = yearDay(
      +new Date(year + 1, 0, 1) / 1000 - 86400
    );
  }
  return arr;
}
function TodayInfo(start) {
  var WEEKLEN = 7,
    WEEKDAYS = ["一", "二", "三", "四", "五", "六", "日"],
    weekInfo = { week: null, day: null },
    oneDay = 24 * 60 * 60 * 1000,
    weekLeave,
    weekStart,
    today,
    dateDiff,
    sDate;
  var rDateStr = /\d{4}[\/-]\d{1,2}[\/-]\d{1,2}/g;
  sDate = new Date(start.replace("-", "/"));
  weekStart = sDate.getDay();
  weekStart = weekStart === 0 ? 7 : weekStart;
  weekLeave = WEEKLEN - weekStart;
  today = new Date();
  weekInfo.day = WEEKDAYS[today.getDay()];
  today = new Date(
    today.getFullYear() + "/" + (today.getMonth() + 1) + "/" + today.getDate()
  );
  dateDiff = today - sDate;
  dateDiff = parseInt(dateDiff / oneDay);
  weekInfo.week = Math.ceil((dateDiff - weekLeave) / WEEKLEN) + 1;
  return weekInfo;
}
var td = TodayInfo("2022/09/05");
import { getDate } from "@/api";
export default {
  data() {
    return {
      tableData: [],
      input: "",
      options: [
        {
          value: "1",
          label: "第 1 周",
        },
        {
          value: "2",
          label: "第 2 周",
        },
        {
          value: "3",
          label: "第 3 周",
        },
        {
          value: "4",
          label: "第 4 周",
        },
        {
          value: "5",
          label: "第 5 周",
        },
        {
          value: "6",
          label: "第 6 周",
        },
        {
          value: "7",
          label: "第 7 周",
        },
        {
          value: "8",
          label: "第 8 周",
        },
        {
          value: "9",
          label: "第 9 周",
        },
        {
          value: "10",
          label: "第 10 周",
        },
        {
          value: "11",
          label: "第 11 周",
        },
        {
          value: "12",
          label: "第 12 周",
        },
        {
          value: "13",
          label: "第 13 周",
        },
        {
          value: "14",
          label: "第 14 周",
        },
        {
          value: "15",
          label: "第 15 周",
        },
        {
          value: "16",
          label: "第 16 周",
        },
      ],
      value: "",
      pageSize: 10,
      currentPage: 1,
      pageCount: null,
      total: null,
      startTime: this.changeValue(td.week).startTime,
      endTime: this.changeValue(td.week).endTime,
      Loading: false,
      server: "无服务",
    };
  },
  created() {
    this.getDate();
  },
  methods: {
    change() {
      this.Loading = true;
      //按回车键响应
      var _this = this;
      _this.search();
      document.onkeydown = function (e) {
        let key = window.event.keyCode;
        if (key == 13) {
          _this.search();
        }
      };
    },
    exportForm() {
      var wb = XLSX.utils.table_to_book(document.querySelector("#mainFrame")); //  mainFrame  table的id
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          "学习时长.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    getDate() {
      this.Loading = true;
      var td = TodayInfo("2022/09/05");
      this.value = "第" + " " + td.week + " " + "周";
      let result = getDate().then(({ data, server }) => {
        if ((result.code = 201)) {
          this.Loading = false;
          this.tableData = data.everyTimeTotal;
          this.pageCount = data.total / this.pageSize;
          this.total = data.total;
          this.server = server;
          this.$emit("fatherMethod", server);
        }
      });
    },
    changeValue(value) {
      let time = whichWeek(year);
      let times = whichWeeks(year);
      let startTimes = time.map((item) => {
        return item.year + "-" + item.month + "-" + item.date;
      });
      let endTimes = times.map((item) => {
        return item.year + "-" + item.month + "-" + item.date;
      });
      this.startTime = startTimes[value - 1];
      this.endTime = endTimes[value - 1];
      return { startTime: this.startTime, endTime: this.endTime };
    },
    search() {
      this.Loading = true;
      this.pageCount = null;
      const params = {
        page: 1,
        size: this.pageSize,
        keyword: this.input,
        startTime: this.startTime,
        endTime: this.endTime,
      };
      let result = getDate(params).then(({ data, server }) => {
        if ((result.code = 201)) {
          this.Loading = false;
          this.tableData = data.everyTimeTotal;
          this.pageCount = data.total / this.pageSize;
          this.total = data.total;
          this.currentPage = 1;
          this.server = server;
          this.$emit("fatherMethod", server);
        }
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
    },
    handleCurrentChange(currentPage) {
      this.Loading = true;
      this.currentPage = currentPage;
      const params = {
        page: this.currentPage,
        size: this.pageSize,
        keyword: this.input,
        startTime: this.startTime,
        endTime: this.endTime,
      };
      let result = getDate(params).then(({ data, server }) => {
        if ((result.code = 201)) {
          this.Loading = false;
          this.tableData = data.everyTimeTotal;
          this.pageCount = data.total / this.pageSize;
          this.total = data.total;
          this.server = server;
          this.$emit("fatherMethod", server);
        }
      });
    },
    keyDown(e) {
      if (e.keyCode == 13) {
        this.Loading = true;
        this.search();
      }
    },
    dstroyed() {
      window.removeEventListener("keydown", this.keyDown, false);
    },
  },
};
</script>

<style lang="scss" scoped>
.header {
  height: 2.5em;
  margin-bottom: 1em;
  .block {
    float: left;
    /deep/ .el-date-editor--daterange.el-input__inner {
      width: 240px;
    }
  }
  .el-select {
    width: 9%;
    float: left;
  }
  .right {
    width: 26em;
    float: right;
  }
  .el-input {
    width: 15em;
  }
  .info {
    margin-right: 1em;
  }
  .sousuo {
    margin-left: 0.3em;
  }
}
.el-pagination {
  margin-top: 2em;
}
</style>
